from flask import Flask, request, make_response
import json
import pymongo
import os
import requests
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
import mdb
from datetime import datetime as dt


app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['file']
        f.save('images_path' + '/' + 'pic1.jpg')
    return 'OK'

@app.route('/<string:filename>', methods=['GET'])
def show_photo(filename):
    if request.method == 'GET':
        if filename is None:
            pass
        else:
            image_data = open('images_path/%s' % filename, "rb").read()
            response = make_response(image_data)
            response.headers['Content-Type'] = 'image/jpg'
            return response


# 创建签到人信息&获取签到人信息
@app.route("/members/<openid>/<signid>", methods=['POST','GET'])
def members(openid,signid):
    if request.method == 'POST':
        c_openid = request.form['c_openid']
        signer = request.form['signer']
        signerDic = json.loads(signer)
        print(c_openid)
        # 加入数据库
        mdb.addSigner(c_openid, signid, signerDic)
        return "ok"

    if request.method == 'GET':
        signInfo = request.args.get('signInfo')
        signInfo = json.loads(signInfo)
        c_openid = signInfo['c_openId']
        print(c_openid)
        sign = mdb.viewOneSign(c_openid, signid)
        signers = sign.get('signers')
        print(sign)
        # 0 为未参与签到， 1 为已经参与签到，但今日未签到  2 为今日已经签到
        if signers is None:  # 签到没有成员的情况
            return 'out'

        # 签到已经有成员，判断当前 openid 是否在签到中
        for s in signers:
            print(s['member_openid'])
            duration = signInfo['duration']
            if s['member_openid'] == openid:
                if duration['forever']:
                    return 'in'
                else:
                    now = dt.now()
                    end = dt.strptime(duration['endDate'] + ' 23:59:59', '%Y-%m-%d %H:%M:%S')
                    if now > end:
                        return 'over'
                    return 'in'
            else:
                return 'out'
        return 'already'

@app.route('/read/<openid>/<signId>', methods = ['POST','GET'])
def createSign(openid,signId):
    if request.method == 'POST':
        signInfo = request.form['signInfo']
        signInfo = json.loads(signInfo)
        # print(signInfo)
        if signInfo['signId']:
            # print(signInfo['signId'])
            mdb.updateSign(signInfo['c_openId'], signInfo)
            return 'update Success'
        else:
            signNum = mdb.createSign(openid, signInfo)
            return 'Create Success'

    if request.method == 'GET':
        print(openid, signId)
        return json.dumps(mdb.viewOneSign(openid, signId))

    return 'OK'

# 查询所有签到信息
@app.route('/viewSigns/<openid>')
def viewSigns(openid):
    return json.dumps(mdb.viewSigns(openid))

# 签到者来签到
@app.route('/signIn/<openid>', methods = ['POST', 'GET'])
def signIn(openid):
    if request.method == 'POST':
        signInfo = request.form['signInfo']
        signInfo = json.loads(signInfo)
        c_openId = signInfo['c_openId']
        signId = signInfo['signId']

        now = dt.now()

        days = signInfo['days']
        if days['allday']:
            startTime = now.date().strftime('%Y-%m-%d') + ' ' + days['startTime']
            startTime = dt.strptime(startTime, '%Y-%m-%d %H:%M')
            endTime = now.date().strftime('%Y-%m-%d') + ' ' + days['endTime']
            endTime = dt.strptime(endTime, '%Y-%m-%d %H:%M')
            if now > startTime and now < endTime:
                mdb.signIn(c_openId, signId, openid)
                return 'success'
        else:
            weekdays = days['weekdays']
            today = weekdays[now.weekday()]
            if today['isSelected']:
                startTime = now.date().strftime('%Y-%m-%d') + ' ' +  today['bgnTime']
                startTime = dt.strptime(startTime, '%Y-%m-%d %H:%M')
                endTime = now.date().strftime('%Y-%m-%d') + ' ' +  today['endTime']
                endTime = dt.strptime(endTime, '%Y-%m-%d %H:%M')
                if now > startTime and now < endTime:
                    mdb.signIn(c_openId, signId, openid)
                    return 'success'
        return 'failed'

@app.route("/getCode", methods=['POST'])
def getCode():
    code = request.form['code']
    # print(code)
    r = requests.get('https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code' % ('wx03c2f48de5914900', '39c2db87c2c357211a2cedb224d940cf', code))
    s = r.content.decode()
    # print(s)
    d = json.loads(s)
    # print(d)
    third_session = d['openid']
    return third_session

def gen_3rdsession(openId):
    # 加密 openid 生成 3rdsession
    s = Serializer(app.config['SECRET_KEY'])
    third_session = s.dumps({'c_openid': openId})
    return third_session

def gen_openId(thirdsession):
    # 用3rdsession解密生成OpenId
    s = Serializer(app.config['SECRET_KEY'])
    openId = s.loads(thirdsession)['c_openid']
    return openId

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0')
